import { defineStore } from "pinia";
import { getValByPath } from "@/utils/tools";

const useUserStore = defineStore("user", {
  state: () => {
    return {
      token: "",
      refreshToken: "",
      roles: ["admin"],
      user: null
    };
  },
  getters: {
    getRoles(state) {
      return state.roles;
    },
    hasRole(state) {
      return role => {
        return state.roles.includes(role);
      };
    },
    getToken(state) {
      return state.token;
    },
    getRefreshToken(state) {
      return state.refreshToken;
    },
    getUser(state) {
      return (path, defaultVal = "") =>
        getValByPath(state.user, path, defaultVal);
    },
    hasLogin(state) {
      return state.token ? true : false;
    }
  },
  actions: {
    setRoles(data: string[]) {
      this.roles = data;
    },
    addRole(data: string) {
      this.roles.push(data);
    },
    setToken(data: string) {
      this.token = data;
    },
    setRefreshToken(data: string) {
      this.refreshToken = data;
    },
    setUser(data: any) {
      this.user = data;
    },
    clear() {
      this.token = "";
      this.refreshToken = "";
      this.user = null;
      this.roles = [];
    }
  },
  persist: {
    paths: ["token", "refreshToken", "user"]
  }
});
export default useUserStore;
